package com.lingkang.xcoa.config.custom;

import com.lingkang.xcoa.data.entity.OaUser;
import com.lingkang.xcoa.service.UserService;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class CustomUserDetailsServiceImpl implements UserDetailsService {

  @Autowired
  private UserService userService;

  @Override
  public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
    //查询用户
    OaUser user = userService.getUserInfo(s);
    if (user == null) {
      throw new UsernameNotFoundException("帐号：" + s + " 不存在！");
    }
    List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
    //查询拥有的角色
    List<String> roles = userService.getRoleByUsername(s);
    roles.forEach(r -> {
      //security的验证规则需要ROLE_USER
      grantedAuthorities.add(new SimpleGrantedAuthority(r));
    });
    //spring5+要求密码加密，我这里传明文密码来加密
    String password = new BCryptPasswordEncoder().encode(user.getPassword());
    return new User(user.getUsername(), password, grantedAuthorities);
  }

}
